package p.sunmes.les.actor.effect;

import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.utils.Align;

import p.sunmes.les.action.CallAction;
import p.sunmes.les.util.U;

/**
 * Excample:</br>
 * 默认isLoop=true
 * <pre>
 * public class EffectArrow extends FrameAnimationActor {

	public EffectArrow() {
		init(3, "effect/arrow/arrow_%d.png", 0.1f);

		for (Image pic : pics) {
			pic.setScale(-0.3f, 0.3f);
		}
	}

 *}
 *</pre>
 */
public class FrameAnimationActor extends Group {
	protected int picCount = 3;
	protected int current;
	protected Image[] pics;
	protected float delay;
	protected float recordDelay;

	protected boolean isLoop = true;
	protected int startIndex = 1;
	protected int endIndex;

	protected CallAction loopEndCall;
	protected boolean isRemoveEndPlay = true;

	public void setIsRemoveEndPlay(boolean isRemove) {
		this.isRemoveEndPlay = isRemove;
	}

	public void setLoopEndCall(CallAction call) {
		this.loopEndCall = call;
	}

	/**
	 * format = xxx/xxx/xx_%d.png , i(picCount) --start with 1.
	 * @param picCount
	 * @param format
	 * @param delay
	 */
	public FrameAnimationActor(int picCount, String format, float delay) {
		init(picCount, format, delay);
	}

	public FrameAnimationActor() {
	}

	/**
	 * <pre>
	 * for (int i = 0; i < pics.length; i++) {
			pics[i].setPosition(x, y, align);
		}
	 * </pre>
	 * @param x
	 * @param y
	 * @param align
	 */
	public void resetPicPosition(float x, float y, int align) {
		for (int i = 0; i < pics.length; i++) {
			pics[i].setPosition(x, y, align);
		}
	}

	/**
	 * format = xxx/xxx/xx_%d.png
	 * @param endIndex
	 * @param format
	 * @param delay
	 */
	public void init(int endIndex, String format, float delay) {
		setTouchable(Touchable.disabled);

		this.picCount = endIndex - startIndex + 1;
		pics = new Image[picCount];
		this.delay = delay;
		this.recordDelay = 0;
		current = 0;
		for (int i = 0; i < picCount; i++) {
			Image pic = U.image(String.format(format, startIndex + i));
			addActor(pic);
			pic.setPosition(0, 0, Align.center);
			pic.setOrigin(Align.center);
			pics[i] = pic;
			pic.setVisible(false);
		}

		pics[0].setVisible(true);
	}

	@Override
	public void act(float delta) {
		super.act(delta);

		recordDelay += delta;
		if (recordDelay >= delay) {
			recordDelay = 0;
			if (current < picCount - 1) {
				pics[current].setVisible(false);
				current++;
				pics[current].setVisible(true);
			} else {
				if (loopEndCall != null) {
					loopEndCall.call();
				}
				if (!isLoop) {
					endCall();
					return;
				}

				pics[current].setVisible(false);
				current = 0;
				pics[current].setVisible(true);
			}
		}
	}

	public void endCall() {
		if (isRemoveEndPlay) {
			remove();
		}
	}
}
